package cn.hpclub.server.controller.client;

import java.util.Date;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.product.ProductOrder;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.service.product.ProductOrderService;
import cn.hpclub.server.service.product.ProductOrderService.SaveProductOrderException;
import cn.hpclub.server.service.product.ProductOrderService.SaveProductOrderToBOSSException;
import cn.hpclub.server.service.product.ProductOrderService.SaveProductOrderToBOSSFail;
import cn.hpclub.server.service.product.ProductService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.OrderType;

/**
 *
 */
@API("/product/order")
public class ProductOrderController extends BaseClientController<ProductOrder>{

    private static final Logger logger = LoggerFactory.getLogger(ProductOrderController.class);

    /**
     * @Title: commit
     * @Description:终端销售提交订单接口，s1. 先检查客户端参数是否有效，s2.再将订单信息保存到大掌柜系统，s3.
     *                             然后调用dpr接口及将订单提交到移动BOSS，s4.等待BOSS接口返回订单状态(
     *                             或者通过回调方式更新)， 及更新dzg订单状态，s5.最后返回BOSS系统订单状态给前端
     */
    public void commit(){
        ProductOrder productOrder = new ProductOrder();
        JSONObject jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "该版本已不支持，请升级最新版本",
                                       ClientApiConstant.Msg.EMPTY);
        
        renderText(jo.toString());
        
        
        /*
        try{
            // step 1. 获取客户端参数，并检查参数是否异常，如参数异常则返回给前端
            getProductOrderObject(productOrder);

            // 产生一个DZG系统的订单编号
            productOrder.setOrder_id(getOrderId());

            logger.info("product-order-commit: " + productOrder.getOrder_id() + ", " + productOrder.getBatch_no() + ", "
                    + productOrder.getMeans_id());

            // step 2. 保存订单数据到大掌柜数据库，因有对两张表的操作，涉及到事务
            ProductOrderService.service.saveProductOrderToDZG(productOrder);

            // step 3. 调用dpr接口保存订单到BOSS系统
            ProductOrderService.service.saveProductOrderToBOSS(productOrder);

            logger.info("product-order-commit success: " + productOrder.getOrder_id() + ", "
                    + productOrder.getBoss_order_id());

            // step 4. 更新DZG订单状态,返回结果不依赖DZG订单保存状态
            // 订单状态：5=新建，10=提交订单到BOSS成功，15=提交订单到BOSS失败
            ProductOrderService.service.updateOrderInfo(productOrder);

            // step 5. 返回给前端订单最终的状态(BOSS系统订单的状态，大掌柜系统订单只是维持一个记录，如有异常都以BOSS系统为准)
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "订单提交成功", ClientApiConstant.Msg.EMPTY);
        }
        catch(IllegalArgumentException e){
            logger.error("客户端提交商品订单参数异常");
            jo = setResponseObj(ClientApiConstant.ResultCode.PARAM_ERROR, "订单提交失败，订单参数异常", ClientApiConstant.Msg.EMPTY);
        }
        catch(SaveProductOrderException e){
            logger.error("商品订单提交到DZG系统失败");
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "订单提交失败", ClientApiConstant.Msg.EMPTY);
        }
        catch(SaveProductOrderToBOSSFail e){
            logger.error("提交订单失败提示语：" + e.getMessage());
            // 更新订单状态为失败状态
            ProductOrderService.service.updateOrderInfo(productOrder);
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, e.getMessage(), ClientApiConstant.Msg.EMPTY);
        }
        catch(SaveProductOrderToBOSSException e){
            logger.error("商品订单提交到BOSS系统异常");
            // 异常，此时订单状态为新建,可以不用去更新
            productOrder.setOrder_status("20");
            ProductOrderService.service.updateOrderInfo(productOrder);
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, e.getMessage(), ClientApiConstant.Msg.EMPTY);
        }
        catch(Exception e){
            logger.error("异常：" + e.getMessage());
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "订单提交异常", ClientApiConstant.Msg.EMPTY);
        }
        finally{
            logger.debug("renderText:" + jo.toString());
            renderText(jo.toString());
        }*/
    }

    private String getOrderId(){
        String dateStr = DateKit.toStr(new Date(), "yyMMdd");

        return OrderType.PRODUCT.getName() + dateStr + InterfaceUtil.getOrderSeq(OrderType.PRODUCT);
    }

    private void getProductOrderObject(ProductOrder obj) throws IllegalArgumentException{
        // BeanConverter.toJavaBean(obj, getParaMap());

        // 销售人员工号
        String login_no = getPara("login_no");
        // 办理的电话号码
        String phone_no = getPara("customer_tel");
        // 查询接口返回的ACT_ID
        String act_id = getPara("act_id");
        // 查询接口返回的MEANS_ID
        String means_id = getPara("means_id");
        // 销售人员工号 渠道编码
        String group_id = getPara("group_id");
        // 终端串号
        String resource_no = getPara("imei");
        // 批次号码，查询接口返回的BATCH_NO
        String batch_no = getPara("batch_no");

        // 销售人员ID
        String sales_id = getPara("sales_id");
        // 手机串号imei
        String imei = resource_no;
        // 订单金额
        String total_price = getPara("total_price");
        // 客户电话号码
        String customer_tel = phone_no;
        // 客户姓名
        String customer_name = getPara("customer_name", "");
        // 商品ID
        String product_id = getPara("product_id");
        // 商品名称
        String product_name = getPara("product_name");
        // 商品标题
        String product_title = getPara("product_title");
        // 商品sku属性
        String product_sku_title = getPara("product_sku_title");
        // 商品sku属性编码
        String product_barcode = getPara("product_barcode", "");
        // 缩略图
        String thumb = getPara("thumb", "");

        if(StrKit.isBlank(thumb) && StrKit.notBlank(product_id)){
            Record record = new ProductService().service.getProductById(Integer.parseInt(product_id));
            thumb = record.getStr("thumbnail");
        }

        // 商品单价
        String unit_price = getPara("unit_price");
        // 商品折扣
        String rebate = getPara("rebate", "0");
        // 商品数量
        String amount = getPara("amount");
        // 合约编码
        String contract_id = getPara("contract_id");
        // 合约详情
        String contract_info = getPara("contract_info");

        // -------------- 服务器后台获取 ------------------
        // 销售人员所属城市
        String city = InterfaceUtil.getCityNameByUserId(sales_id);
        // 销售人员机构ID
        String org_id = InterfaceUtil.getOrgIdByUserId(sales_id);

        // 检查必填字段
        if(StrKit.isBlank(login_no) || StrKit.isBlank(phone_no) || StrKit.isBlank(act_id) || StrKit.isBlank(means_id)
                || StrKit.isBlank(group_id) || StrKit.isBlank(resource_no) || StrKit.isBlank(batch_no)){
            throw new IllegalArgumentException("参数错误1");
        }

        // 检查必填字段
        if(StrKit.isBlank(sales_id) || StrKit.isBlank(org_id) || StrKit.isBlank(imei) || StrKit.isBlank(customer_tel)
                || StrKit.isBlank(total_price) || StrKit.isBlank(product_id) || StrKit.isBlank(product_name)
                || StrKit.isBlank(product_title) || StrKit.isBlank(product_sku_title) || StrKit.isBlank(unit_price)
                || StrKit.isBlank(amount) || StrKit.isBlank(contract_id) || StrKit.isBlank(contract_info)){
            throw new IllegalArgumentException("参数错误2");
        }

        // 检查必填字段
        // if(StrKit.isBlank(sales_id) || StrKit.isBlank(org_id) ||
        // StrKit.isBlank(imei) || StrKit.isBlank(customer_tel)
        // || StrKit.isBlank(total_price) || StrKit.isBlank(customer_name) ||
        // StrKit.isBlank(product_id)
        // || StrKit.isBlank(product_name) || StrKit.isBlank(product_title) ||
        // StrKit.isBlank(product_sku_title)
        // || StrKit.isBlank(product_barcode) || StrKit.isBlank(thumb) ||
        // StrKit.isBlank(unit_price)
        // || StrKit.isBlank(rebate) || StrKit.isBlank(amount) ||
        // StrKit.isBlank(contract_id)
        // || StrKit.isBlank(contract_info)){
        // throw new IllegalArgumentException("参数错误2");
        // }

        if(StrKit.isBlank(city) || StrKit.isBlank(org_id)){
            throw new IllegalArgumentException("参数错误3");
        }

        obj.setLogin_no(login_no);
        obj.setPhone_no(phone_no);
        obj.setAct_id(act_id);
        obj.setMeans_id(means_id);
        obj.setGroup_id(group_id);
        obj.setResource_no(resource_no);
        obj.setBatch_no(batch_no);

        obj.setAmount(amount);
        obj.setSales_id(sales_id);
        obj.setContract_id(contract_id);
        obj.setContract_info(contract_info);
        obj.setImei(imei);
        obj.setCustomer_name(customer_name);
        obj.setCustomer_tel(customer_tel);
        obj.setProduct_barcode(product_barcode);
        obj.setProduct_id(product_id);
        obj.setProduct_name(product_name);
        obj.setProduct_sku_title(product_sku_title);
        obj.setProduct_title(product_title);
        obj.setRebate(rebate);
        obj.setTotal_price(total_price);
        obj.setThumb(thumb);
        obj.setUnit_price(unit_price);

        obj.setOrg_id(org_id);
        obj.setCity(city);
    }

    /**
     * @Title: list
     * @Description:获取员工相关的订单列表 void
     */
    public void list(){
        String userId = getPara("sales_id");
        String result = ProductOrderService.service.getOrderList(userId);
        logger.debug("result=" + result);
        renderText(result);
    }

    public void detail(){
        String orderId = getPara("order_id");
        String result = ProductOrderService.service.getOrderDetail(orderId);
        logger.debug("result=" + result);
        renderText(result);
    }
}
